package com.lupan.tomcatStudy.jndi.handle;

import com.lupan.tomcatStudy.jndi.domain.Student;
import com.lupan.tomcatStudy.jndi.service.EmailService;
import com.lupan.tomcatStudy.jndi.service.JNDIService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 说明：处理servlet映射过来的方法调用
 *
 * @author lupan
 * @version 2016/6/30 10:44
 */
public class MyHttpHandle {

    private static volatile MyHttpHandle instance;

    private MyHttpHandle(){

    }

    public static MyHttpHandle getInstance(){
        if(instance==null){
            synchronized (MyHttpHandle.class){
                if(instance==null){
                    instance = new MyHttpHandle();
                }
            }
            return instance;
        }
        return instance;
    }


    private EmailService emailService = EmailService.getInstance();
    private JNDIService jndiService = JNDIService.getInstance();

    public void sendEmail(HttpServletRequest req,HttpServletResponse resp){
        String[] addresses = req.getParameter("address").split(",");
        String subject = req.getParameter("subject");
        String content = req.getParameter("content");
        emailService.sendEmail(addresses,subject,content);
        try {
            resp.setCharacterEncoding("utf-8");
            resp.getWriter().write("发送邮件成功！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void getDataSource(HttpServletRequest req,HttpServletResponse resp){
        Student student = jndiService.getDataSource();
        try {
            resp.setCharacterEncoding("utf-8");
            resp.getWriter().write(student.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void getBeanByJNDI(HttpServletRequest req, HttpServletResponse resp) {
        com.lupan.bean.Student student = jndiService.getBeanByJNDI();
        try {
            resp.setCharacterEncoding("utf-8");
            resp.getWriter().write(student.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
